package com.mezz.bones.framework.web.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.framework.base.domain.enums.ResponseCode;
import com.mezz.bones.framework.base.domain.response.Result;
import com.mezz.bones.framework.cache.redis.service.RedisService;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: zhuang
 * @Date: 2024/7/12 17:40
 * @Description: 过滤某些接口请求
 * @Version: 1.0
 **/
@Component
@RequiredArgsConstructor
public class ApiDisableFilter implements Filter {

    private final RedisService redisService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        String requestURI = httpRequest.getRequestURI();

        // 检查接口状态
        if (isInterfaceDisabled(requestURI)) {
            JakartaServletUtil.write(httpResponse, JSONObject.toJSONString(Result.error(ResponseCode.API_DISABLE_ERROR)),"application/json;charset=utf-8");

            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);

    }

    private boolean isInterfaceDisabled(String requestURI) {
        // 从数据库查询接口状态
        List<String> disabledEndpoints = new ArrayList<>();
        disabledEndpoints.add("/disable");
        return disabledEndpoints.contains(requestURI);
    }

}
